#include "textview.h"
#include <QPainter>
#include <QMouseEvent>
#include <QPoint>
#include "common.h"
#include <QApplication>
#include <QEvent>
#include <QHBoxLayout>


int TextView::m_id = qRegisterMetaType<TextView*>();

TextView::TextView(QWidget *parent)
    : ViewObject(parent)
    ,m_label(NULL)
    ,m_paramTextView(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_DeleteOnClose);
    m_label = new QLabel(this);
    m_label->setAlignment(Qt::AlignCenter);
    m_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(m_label, 0, Qt::AlignCenter);
    layout->setContentsMargins(0, 0, 0, 0);
    setContentsMargins(0, 0, 0, 0);
    setLayout(layout);
#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
        m_objectParam = new ParamObject;

    if (m_paramTextView == NULL)
        m_paramTextView = new TextViewParam;
}


TextView::~TextView()
{
    DestoryObject();
}


void TextView::DestoryObject()
{
    HideObject();

    if (m_objectParam != NULL)
        delete  m_objectParam;

    m_objectParam = NULL;

    if (m_paramTextView != NULL)
        delete m_paramTextView;

    m_paramTextView = NULL;

    close();
}

void TextView::HideObject()
{
    setParent(NULL);
    hide();
}

void TextView::ShowObject()
{

    if (m_paramTextView == NULL || m_objectParam == NULL) return;

    location(m_objectParam->GetX(), m_objectParam->GetY(),
                m_objectParam->GetWidth(), m_objectParam->GetHeight());
    m_label->setFixedSize(size());

    if (m_paramTextView->m_textContent == "")
    {
        m_paramTextView->m_textContent = m_objectParam->GetObjectName();
    }
    m_label->setText(m_paramTextView->m_textContent);

    if (m_paramTextView->m_textFormat != "")
    {
        QStringList format_list = m_paramTextView->m_textFormat.split("\n");
        QString format_qss = styleSheet();
        for (int i = 0; i < format_list.size(); i++)
        {
            if(format_list.at(i).contains(";"))
            {
               format_qss.append(format_list.at(i));
            }
            else
            {
                QFont f;
                if (f.fromString(format_list.at(i)))
                    m_label->setFont(f);
            }
        }
        setStyleSheet(format_qss);
    }
    show();
}

void TextView::GetAttribute(std::string& attribute)
{
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();

    base["content"] = m_paramTextView->m_textContent.toStdString();
    base["style"] = m_paramTextView->m_textFormat.toStdString();
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void TextView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
    {
         LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);
    }

    if(CheckJsonValueType(root,"zindex",Json::stringValue))
    {
       m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"stid",Json::stringValue))
    {
        m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());
    }
    if(CheckJsonValueType(root,"x",Json::stringValue))
    {
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"y",Json::stringValue))
    {
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"w",Json::stringValue))
    {
         m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"h",Json::stringValue))
    {
         m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"name",Json::stringValue))
    {
         m_objectParam->SetName(QString::fromStdString(root["name"].asString()));
    }

    if(CheckJsonValueType(root,"content",Json::stringValue))
    {
        m_paramTextView->m_textContent = QString::fromStdString(root["content"].asString());
    }

    if(CheckJsonValueType(root,"style",Json::stringValue))
    {
        m_paramTextView->m_textFormat = QString::fromStdString(root["style"].asString());
    }

    if (CheckJsonValueType(root, "id", Json::stringValue))
    {
        m_objectParam->SetStIdType(QString::fromStdString(root["id"].asString()));
    }
    if (CheckJsonValueType(root, "idtype", Json::stringValue))
    {
        m_objectParam->SetStIdType(QString::fromStdString(root["idtype"].asString()));
    }
}

void TextView::ParseXML(QDomElement* xmlDomEle)
{
    if(m_paramTextView == NULL)
    {
        m_paramTextView = new TextViewParam;
    }
    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name",""));

    QDomNodeList paramlist = xmlDomEle->childNodes();
    for(int listcnt = 0; listcnt < paramlist.count(); listcnt++)
    {
        QDomElement param = paramlist.item(listcnt).toElement();
        if(param.isComment()||param.isNull())
        {
            continue;
        }
        QString temp = param.attribute("content","");
        if(temp != "")
        {
            m_paramTextView->m_textContent = temp;
        }
        temp = param.attribute("style","");
        if(temp != "")
        {
            m_paramTextView->m_textFormat = temp;
        }
    }

}

void TextView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type", m_objectParam->GetObjectName());
    dom->setAttribute("zindex",QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid",QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x",QString::number(m_objectParam->GetX()));
    dom->setAttribute("y",QString::number(m_objectParam->GetY()));
    dom->setAttribute("w",QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h",QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name",m_objectParam->GetName());

    QDomElement dom1 = document.createElement("param");
    dom1.setAttribute("content", m_paramTextView->m_textContent);
    dom->appendChild(dom1);

    QDomElement dom2 = document.createElement("param");
    dom2.setAttribute("style", m_paramTextView->m_textFormat);
    dom->appendChild(dom2);
    LOG_QDEBUG<<__func__<<m_paramTextView->m_textFormat;
}



